home *** CD-ROM | disk | FTP | other *** search
- Path: grimsel.zurich.ibm.com!usenet
- From: wgk@zurich.ibm.com (Keith Whittingham)
- Newsgroups: comp.lang.c++
- Subject: Re: Is this a memory leak?
- Date: 4 Apr 1996 08:58:13 GMT
- Organization: IBM Research, ZRH
- Message-ID: <4k02v5$tu7@grimsel.zurich.ibm.com>
- References: <4jv214$gv7@insosf1.netins.net>
- Reply-To: wgk@zurich.ibm.com
- NNTP-Posting-Host: pine.zurich.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.00
-
- In <4jv214$gv7@insosf1.netins.net>, hhowe@trgnet.com (Harold Howe) writes:
- >Could someone please tell me if this code leaks memory
- >
- >class BuriedClass
- > {
- > ...
- > }
- >
- >class TopClass
- > {
- > private
- > BuriedClass *bury;
- > public:
- > TopClass::TopClass() { bury = new BuriedClass();}
- > shutDown { bury = 0;}
- > ~TopClass { delete bury}
- > }
- >
- >int main(void)
- > {
- > TopClass *top = new TopClass();
- > top->shutDown();
- > delete top;
- > return 0;
- > }
- >
- Yup, memory leak alright!
-
- The ctor allocates a block of memory for the BuriedClass, probably calling
- a malloc(). "bury" is a variable which is set to point at that memory, i.e
- it is assigned a value equal to the address of the allocated memory.
-
- The shutDown method does nothing more or less than assigning a value of
- 0 to the bury variable - the is no delete/free of the memory.
-
- The dto, ~TopClass, is a going to try and free some memory at the address
- 0x000 but, by a quirk of implmentation, will probably not blow up (as a
- simple call to free(0) would). Instead the compiler probably generates
- code to check that the object address is 0, it so there is no deallocation
- of the memory.
-
- Better to forget about the shutdown function and either to simply declare
- bury as a member variable:
-
- class TopClass
- {
- private
- BuriedClass bury; // note no '*'
- public:
- TopClass::TopClass() { }
- ~TopClass { }
- }
-
- or if you really want to do it dynamically...
-
- class TopClass
- {
- private
- BuriedClass *bury;
- public:
- TopClass::TopClass() { bury = new BuriedClass; }
- ~TopClass { delete bury; }
- }
-
-
- The first approach is better.
-
- Keith
-
-